<?php

namespace zhtfrontend\models\datas;

use common\components\extenders\MenuManage;
use common\models\datas\IsuserInfo;
use Yii;

/**
 * This is the model class for table "dmd_coupons_code".
 *
 * @property integer $id
 * @property integer $coupons_id
 * @property string $code
 * @property integer $salesman_id
 * @property integer $status
 * @property integer $is_use
 * @property integer $create_at
 */
class CouponsCode extends \zhtfrontend\components\bases\BaseModel
{

    public $number;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%coupons_code}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['coupons_id', 'salesman_id', 'status', 'is_use', 'create_at','number'], 'integer'],
            [['coupons_id', 'salesman_id', 'number'], 'required'],
            [['code'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('zhtfrontend', 'ID'),
            'coupons_id' => Yii::t('zhtfrontend', '优惠券ID'),
            'code' => Yii::t('zhtfrontend', '券码'),
            'salesman_id' => Yii::t('zhtfrontend', '领券人ID'),
            'status' => Yii::t('zhtfrontend', '是否领取'),
            'is_use' => Yii::t('zhtfrontend', '是否使用'),
            'create_at' => Yii::t('zhtfrontend', '领取时间'),
            'number' => Yii::t('zhtfrontend', '领取数量')
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['create_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->create_at);
        };
        $fields['status'] = function (){
            switch ($this->status){
                case '0':
                    return \Yii::t('zhtfrontend','未领取');
                case '1';
                    return \Yii::t('zhtfrontend','已领取');
            }
        };
        $fields['is_use'] = function (){
            switch ($this->is_use){
                case '0':
                    return \Yii::t('zhtfrontend','未使用');
                case '1';
                    return \Yii::t('zhtfrontend','已使用');
            }
        };
        $fields['salesman_id'] = function (){
            $salesman = IsuserInfo::find()->where(['id'=>$this->salesman_id])->one();
            return $salesman->contact;
        };

        return $fields;
    }

    public function extraFields()
    {
        return [
            'coupons_name' => function () {
                return isset($this->coupons)?$this->coupons->name:'';
            },
            'invalid_time' => function(){
                return isset($this->coupons->end_time)?\Yii::$app->formatter->asDate($this->coupons->end_time):'';
            }
        ];
    }

    public function getCoupons(){
        return $this->hasOne(Coupons::className(),['id'=>'coupons_id']);
    }

}
